package com.wgts.wgts.mvp.model.imp;

import com.wgts.wgts.mvp.model.ISendSMSCodeModel;
import com.wgts.wgts.netmodle.HttpResultSubscriber;
import com.wgts.wgts.netmodle.NetService;
import com.wgts.wgts.netmodle.TransformUtils;
import com.wgts.wgts.netmodle.req.SmsCodeRequest;
import com.wgts.wgts.netmodle.resp.CurrentEntity;
import com.wgts.wgts.rxjava.MVPResultSubscriber;
import com.wgts.wgts.tools.CountDownTime;
import com.wgts.wgts.tools.CountDownTimerListener;

import rx.Observable;
import rx.Subscriber;

public class SendSMSCodeModel implements ISendSMSCodeModel {

    private NetService netService;

    private CountDownTime countDownTime;

    private CountDownTimerListener listener;

    private int codeTime = 60;

    public SendSMSCodeModel(NetService netService, CountDownTime countDownTime) {
        this.netService = netService;
        this.countDownTime = countDownTime;
    }

    @Override
    public void sendSMS(SmsCodeRequest request, HttpResultSubscriber<CurrentEntity> subscriber) {
        netService.sendSMS(subscriber, request);
    }

    @Override
    public void setCutDownTime(final MVPResultSubscriber<Integer> subscriber) {

        if(listener == null){
            codeTime = 60;
            listener = new CountDownTimerListener() {
                @Override
                public void countDownTimerListener() {
                    Observable.create(new Observable.OnSubscribe<Integer>() {
                        @Override
                        public void call(Subscriber<? super Integer> subscriber) {
                            codeTime--;
                            if(codeTime == 0){
                                countDownTime.removeCountDownTimerListener(listener);
                                listener = null;
                            }
                            subscriber.onNext(codeTime);
                        }
                    }).compose(TransformUtils.<Integer>defaultSchedulers()).subscribe(subscriber);
                }
            };
        }

        countDownTime.addCountDownTimerListener(listener);
    }

    @Override
    public void removeCutDownTime() {
        countDownTime.removeCountDownTimerListener(listener);
        listener = null;
    }
}
